package com.joey.concurrency.example.queue;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @Author hyy
 **/
@Slf4j
public class ArrayBlockingQueueExample2 {

    static ArrayBlockingQueue<Integer> linkedBlockingQueue = new ArrayBlockingQueue<Integer>(2);

    public static void main(String[] args) {
        ProducerThread1 p = new ProducerThread1();
        ConsumerThread1 c = new ConsumerThread1();
        p.start();
        c.start();
    }
}

class ProducerThread1 extends Thread{

    @Override
    public void run(){
        System.out.println("PUT START");
        for (int i = 5; i < 120; i++) {
            try {
                if(i / 4 == 0){
                    Thread.sleep(1000);
                }
                ArrayBlockingQueueExample2.linkedBlockingQueue.put(i);
                System.out.println("PUT "+i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("PUT END");
    }
}

class ConsumerThread1 extends Thread{

    @Override
    public void run(){
        System.out.println("POLL START");
        int rows = 0;
        while (true){
            try {
                if(ArrayBlockingQueueExample2.linkedBlockingQueue.size() > 0){
                    Integer value = ArrayBlockingQueueExample2.linkedBlockingQueue.poll();
                    System.out.println("POLL "+value);
                    rows++;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            if(rows == 9){
                break;
            }
        }
        System.out.println("POLL END");

    }
}
